package com.google.gsaguide.DAO;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gsaguide.gsa.Ambassador;

import java.util.ArrayList;
import java.util.List;

//TODO: Need to improve some comments. @Jordan

/**
 * Created by Jordan on 01/07/14.
 */
public class AmbassadorDAO {
    //Singleton
    private static AmbassadorDAO ambDaoSingle;
    //Constants
    private final String[] GET_ALL = {
            SQLConnection.COLUMN_ID,
            SQLConnection.COLUMN_NAME,
            SQLConnection.COLUMN_UNIVERSITY,
            SQLConnection.COLUMN_LOCATION,
            SQLConnection.COLUMN_PROFILE_URL,
            SQLConnection.COLUMN_IMAGE_URL
    };
    //Database variables
    private SQLiteDatabase database;
    private SQLConnection connection;

    private AmbassadorDAO(Context context) {
        connection = new SQLConnection(context);
    }

    public static AmbassadorDAO getInstance(Context ctx) {
        if (ambDaoSingle == null) {
            ambDaoSingle = new AmbassadorDAO(ctx);
        }
        return ambDaoSingle;
    }


    /**
     * Save an ambassador on database if the ambassador doesn't exist.
     * If the ambassador already exist, it just update
     *
     * @param ambassador the ambassador object
     * @return true if was successful, false if something went wrong
     */
    public boolean add(Ambassador ambassador) {

        if (exists(ambassador))
            return update(ambassador);

        database = connection.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(SQLConnection.COLUMN_ID, ambassador.getId());
        values.put(SQLConnection.COLUMN_NAME, ambassador.getName());
        values.put(SQLConnection.COLUMN_UNIVERSITY, ambassador.getUniversity());
        values.put(SQLConnection.COLUMN_LOCATION, ambassador.getLocation());
        values.put(SQLConnection.COLUMN_PROFILE_URL, ambassador.getProfileURL());
        values.put(SQLConnection.COLUMN_IMAGE_URL, ambassador.getPhotoURL());

        return database.insert(SQLConnection.TABLE_AMBASSADORS, null, values) != -1 ? true : false;
    }

    /**
     * Get an ambassador from database
     *
     * @param id the id from the ambassador
     * @return the ambassador object, or empty if nothing is found
     */
    public Ambassador get(String id) {
        database = connection.getReadableDatabase();

        Cursor cursor = database.query(
                SQLConnection.TABLE_AMBASSADORS,
                GET_ALL,
                " id = ?",
                new String[]{id},
                null,
                null,
                null,
                null);

        if (cursor == null)
            return null;
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            Ambassador ambassador = new Ambassador();
            ambassador.setId(cursor.getString(0));
            ambassador.setName(cursor.getString(1));
            ambassador.setUniversity(cursor.getString(2));
            ambassador.setLocation(cursor.getString(3));
            ambassador.setProfileURL(cursor.getString(4));
            ambassador.setPhotoURL(cursor.getString(5));

            return ambassador;
        }
        return null;

    }

    /**
     * Update an ambassador from database, deleting the old and add the updated
     *
     * @return if was successful
     */
    public boolean update(Ambassador ambassador) {
        return delete(ambassador.getId()) && add(ambassador);
    }

    /**
     * Delete an ambassador of the database
     *
     * @param id the id of ambassador in the database
     * @return if was successful
     */
    public boolean delete(String id) {
        database = connection.getWritableDatabase();

        String selection = "id LIKE ?";
        String[] selectionArgs = {id};

        return database.delete(SQLConnection.TABLE_AMBASSADORS, selection, selectionArgs) == 1 ? true : false;
    }

    /**
     * Returns all the Ambassadors saved in the database.
     *
     * @return - List containing all the Ambassadors stored in the database.
     * @author Felipe Porge Xavier - http://www.felipeporge.com
     */
    public List<Ambassador> getAll() {
        List<Ambassador> ambList = new ArrayList<Ambassador>();
        database = connection.getReadableDatabase();

        Cursor cursor = database.query(SQLConnection.TABLE_AMBASSADORS, GET_ALL, null, null, null, null, null, null);

        if (cursor == null)
            return null;

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Ambassador ambassador = new Ambassador();
                ambassador.setId(cursor.getString(0));
                ambassador.setName(cursor.getString(1));
                ambassador.setUniversity(cursor.getString(2));
                ambassador.setLocation(cursor.getString(3));
                ambassador.setProfileURL(cursor.getString(4));
                ambassador.setPhotoURL(cursor.getString(5));
                // Adding Ambassador to the list
                ambList.add(ambassador);
            } while (cursor.moveToNext());
        }
        return ambList;
    }

    public void close() {
        if ((database != null) && database.isOpen())
            database.close();
    }

    /**
     * Check if an Ambassador exist
     *
     * @param ambassador - The ambassador that you want to see if exist
     * @return - True if this ambassador already exists in the database.
     */
    public boolean exists(Ambassador ambassador) {
        database = connection.getReadableDatabase();
        final String[] GET_ID = {SQLConnection.COLUMN_ID};
        Cursor cursor = database.query(
                SQLConnection.TABLE_AMBASSADORS,
                GET_ID,
                " id = ?",
                new String[]{ambassador.getId()},
                null,
                null,
                null,
                null
        );
        if (cursor == null)
            return false;
        return cursor.getCount() > 0;
    }

    /**
     * Check if an Ambassador exist
     *
     * @param id - The ambassador's id that you want to see if exist
     * @return - True if this ambassador already exists in the database.
     */
    public boolean exists(String id) {
        database = connection.getReadableDatabase();
        final String[] GET_ID = {SQLConnection.COLUMN_ID};
        Cursor cursor = database.query(
                SQLConnection.TABLE_AMBASSADORS,
                GET_ID,
                " id = ?",
                new String[]{id},
                null,
                null,
                null,
                null
        );
        if (cursor == null)
            return false;
        return cursor.getCount() > 0;
    }

    public ArrayList<Ambassador> getByNameAndUniversity(String prefix) {
        database = connection.getReadableDatabase();
        ArrayList<Ambassador> list = new ArrayList<Ambassador>();
        String[] prefixo = {prefix + "%"};

        Cursor cursor = database.rawQuery("SELECT * FROM " + SQLConnection.TABLE_AMBASSADORS + " WHERE " + SQLConnection.COLUMN_NAME + " LIKE ?", prefixo);
        Cursor cursor2 = database.rawQuery("SELECT * FROM " + SQLConnection.TABLE_AMBASSADORS + " WHERE " + SQLConnection.COLUMN_UNIVERSITY + " LIKE ?", prefixo);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Ambassador ambassador = new Ambassador();
                ambassador.setId(cursor.getString(0));
                ambassador.setName(cursor.getString(1));
                ambassador.setUniversity(cursor.getString(2));
                ambassador.setLocation(cursor.getString(3));
                ambassador.setProfileURL(cursor.getString(4));
                ambassador.setPhotoURL(cursor.getString(5));
                // Adding Ambassador to the list
                list.add(ambassador);
            } while (cursor.moveToNext());
        }
        // looping through all rows and adding to list
        if (cursor2.moveToFirst()) {
            do {
                Ambassador ambassador = new Ambassador();
                ambassador.setId(cursor2.getString(0));
                ambassador.setName(cursor2.getString(1));
                ambassador.setUniversity(cursor2.getString(2));
                ambassador.setLocation(cursor2.getString(3));
                ambassador.setProfileURL(cursor2.getString(4));
                ambassador.setPhotoURL(cursor2.getString(5));
                // Adding Ambassador to the list
                list.add(ambassador);
            } while (cursor2.moveToNext());
        }

        Log.v("----------------", "-------------------------");
        for (Ambassador amb : list) {
            Log.v("PESQUISA: ", amb.getName() + "   " + amb.getUniversity());
        }
        Log.v("----------------", "-------------------------");
        return list;

    }

}
